//
//  AddMaterialViewController.m
//  Article
//
//  Created by LONG on 16/4/21.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "AddMaterialViewController.h"
#import "CaptureViewController.h"
#import "BannerViewController.h"

@interface AddMaterialViewController ()<UITextFieldDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UIAlertViewDelegate,PassImageDelegate>

@property (weak, nonatomic) IBOutlet UIButton *tongLBut;
@property (weak, nonatomic) IBOutlet UIButton *mingPBut;//名片

@property (weak, nonatomic) IBOutlet UIButton *cutOutBut;

@property (nonatomic,strong)NSMutableArray *arrBut;

@property (nonatomic,strong)UIImageView *image;
@property (nonatomic,strong)UIImageView *mingPimage;

@property (nonatomic,strong)UIView *tongLView;
@property (nonatomic,strong)UIView *mingPView;

@property (nonatomic,strong)NSString *bannertext_id;

@property (nonatomic,strong)NSString *colorNomer;


@end

@implementation AddMaterialViewController{
    UIActionSheet * _action;
    UIImagePickerController *_myPicker;
    
    NSString *_type;//类型

    NSString *_imageurlstr;//图片str
    NSString *_ad_cut;//剪裁
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"添加素材";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    [self.navigationItem.leftBarButtonItem setTintColor:UIColorFromRGB(0xffffff)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(addview)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:UIColorFromRGB(0xffffff)} forState:UIControlStateNormal];
    
    _myPicker = [[UIImagePickerController alloc]init];
    _myPicker.view.backgroundColor = [UIColor clearColor];
    _myPicker.allowsEditing = YES;
    _myPicker.delegate = self;
    _myPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    _myPicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    
    _arrBut = [[NSMutableArray alloc]init];
    [_arrBut addObject:_tongLBut];
    
    [_arrBut addObject:_mingPBut];

    //添加素材
    if (self.pushint==1) {
        self.cutOutBut.hidden = YES;
        _type = @"banner";

        [self tongLView];
        _ad_cut = @"0";
    }
    //编辑素材
    else{
        self.navigationItem.title = @"编辑素材";
        
        _ad_cut = @"0";
        
        _mingPBut.hidden = YES;
        
        _tongLBut.userInteractionEnabled = NO;

        if ([self.setTitle isEqualToString:@"通栏"]){
            [self tongLView];
            [_tongLBut setTitle:@"广告素材" forState:UIControlStateNormal];
            _type = @"banner";
        }
        else if ([self.setTitle isEqualToString:@"名片"]){
            [self mingPView];
            [_tongLBut setTitle:@"名片素材" forState:UIControlStateNormal];

            _type = @"vcard";
        }
        
    }

    
}
- (void)addview{
    
    if(_banner_id){
        [self TextBeComposedOfView];
    }else{
        [self PreserveView];
    }
}
- (void)PreserveView{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    
    if ([_type isEqualToString:@"banner"]) {
        
        UITextField *ad_link = (id)[self.view viewWithTag:130];
        
        [dic setValue:@"banner" forKey:@"type"];
        if(_banner_id){
            [dic setValue:[NSString stringWithFormat:@"%@",_bannertext_id] forKey:@"ad_img"];
        }else{
            [dic setValue:[NSString stringWithFormat:@"%@",_imageurlstr] forKey:@"ad_img"];
        }
        [dic setValue:[NSString stringWithFormat:@"%@",ad_link.text] forKey:@"ad_link"];
        
        
    }else if ([_type isEqualToString:@"vcard"]){
        
        UITextField *ad_title = (id)[self.view viewWithTag:134];
        UITextView *ad_describe = (id)[self.view viewWithTag:135];
        UITextField *ad_name = (id)[self.view viewWithTag:136];
        UITextField *ad_mobile = (id)[self.view viewWithTag:137];
        UITextField *ad_address = (id)[self.view viewWithTag:138];
        UITextField *ad_qqtext = (id)[self.view viewWithTag:139];
        UITextField *ad_wxtext = (id)[self.view viewWithTag:140];

        [dic setValue:@"vcard" forKey:@"type"];
        
        if (self.pushint==1) {
            [dic setValue:[NSString stringWithFormat:@"%@",_imageurlstr] forKey:@"ad_head"];

        }

        [dic setValue:[NSString stringWithFormat:@"%@",ad_title.text] forKey:@"ad_card_title"];
        [dic setValue:[NSString stringWithFormat:@"%@",ad_describe.text] forKey:@"ad_card_description"];
        [dic setValue:[NSString stringWithFormat:@"%@",ad_name.text] forKey:@"ad_name"];
        [dic setValue:[NSString stringWithFormat:@"%@",ad_mobile.text] forKey:@"ad_mobile"];
        [dic setValue:[NSString stringWithFormat:@"%@",ad_address.text] forKey:@"ad_address"];
        [dic setValue:[NSString stringWithFormat:@"%@",ad_qqtext.text] forKey:@"ad_qq"];
        [dic setValue:[NSString stringWithFormat:@"%@",ad_wxtext.text] forKey:@"ad_wx"];

    }
    
    
    [dic setValue:_banner_id forKey:@"ad_banner_id"];
    [dic setValue:_ad_cut forKey:@"ad_cut"];
    [dic setValue:[user objectForKey:@"token"] forKey:@"user_token"];
    //添加素材
    if (!(self.pushint==1)) {
        [dic setValue:[NSString stringWithFormat:@"%@",_ads_id] forKey:@"ads_id"];
        
    }
    NSLog(@">>>>>%@",dic);
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:ADDADS_URL parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([[responseObject objectForKey:@"status"] intValue] == 1) {
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }
        NSLog(@"添加广告%@",[responseObject objectForKey:@"info"] );
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];

}
- (void)TextBeComposedOfView{
    
    
    UITextField *textview1 = (id)[self.view viewWithTag:131];
    UITextField *textview2 = (id)[self.view viewWithTag:132];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    
    [dic setValue:_banner_id forKey:@"banner_id"];
    [dic setValue:[NSString stringWithFormat:@"%@",textview1.text] forKey:@"text"];
    [dic setValue:[NSString stringWithFormat:@"%@",textview2.text] forKey:@"sub"];
    if (_colorNomer) {
        [dic setValue:_colorNomer forKey:@"color"];
    }else{
        [dic setValue:@"#000000" forKey:@"color"];
    }
    NSLog(@">>>%@",dic);
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:BANNEREDIT_URL parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        
        
        if ([[responseObject objectForKey:@"status"] intValue] == 1) {
            NSLog(@"文字合成成功,%@,%@",[responseObject objectForKey:@"path"],[responseObject objectForKey:@"id"]);
            _bannertext_id = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"id"]];
            [self PreserveView];
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        NSLog(@"ddddddd");
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];

}

//裁剪
- (void)tailorBut:(UIButton *)sender {
    
    if (sender.selected) {
        sender.selected = NO;
        _ad_cut = @"0";
        [sender setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateSelected];
    }else{
        sender.selected = YES;
        _ad_cut = @"1";
        [sender setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateSelected];
    }
}

- (IBAction)typeBut:(UIButton *)sender {
    for (UIButton *but in _arrBut) {
        [but setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
        [but setBackgroundColor:UIColorFromRGB(0xffffff)];
    }
    [sender setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];
    [sender setBackgroundColor:UIColorFromRGB(MYColor)];
    
    if (_tongLView) {
        [_tongLView removeFromSuperview];
        _tongLView = nil;
    }
        if (_mingPView){
            [_mingPView removeFromSuperview];
            _mingPView = nil;
        }
    switch (sender.tag) {
        case 70:
            [self tongLView];
            _type = @"banner";
            
            break;
        case 71:
        [self mingPView];
        _type = @"vcard";
        break;
            
        default:
            break;
    }

}

- (UIView *)tongLView{
    if (_tongLView == nil) {
        _tongLView = [[UIView alloc]init];
        _tongLView.frame = CGRectMake(0, 52, WIDTH, 288);
        [self.view addSubview:_tongLView];
        
        UILabel *telab = [[UILabel alloc]initWithFrame:CGRectMake(8, 9, 65, 20)];
        telab.text = @"是否剪裁:";
        telab.font = [UIFont systemFontOfSize:14];
        telab.textColor = [UIColor blackColor];
        [_tongLView addSubview:telab];
        
        UIButton *tailorBut = [[UIButton alloc]initWithFrame:CGRectMake(75, 8, 40, 22)];
        [tailorBut setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [tailorBut addTarget:self action:@selector(tailorBut:) forControlEvents:UIControlEventTouchUpInside];
        [_tongLView addSubview:tailorBut];

        UILabel *xianLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 38, WIDTH , 1)];
        xianLab.backgroundColor = UIColorFromRGB(0xEFEFF1);
        [_tongLView addSubview:xianLab];
        
        _image = [[UIImageView alloc]initWithFrame:CGRectMake(10, 48, WIDTH-20, 80)];
        if ([_dataDic objectForKey:@"ad_img"]) {
            [_image sd_setImageWithURL:[NSURL URLWithString:[_dataDic objectForKey:@"ad_img"]]];
        }else{
            _image.image = [UIImage imageNamed:@"tonglan"];
        }

        _image.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singlepress:)];
        [_image addGestureRecognizer:singleTap1];
        [_tongLView addSubview:_image];
        
        UIImageView *urlimage = [[UIImageView alloc]initWithFrame:CGRectMake(15, 143, 15, 15)];
        urlimage.image = [UIImage imageNamed:@"Unknown"];
        [_tongLView addSubview:urlimage];
        
        UIImageView *urlimage1 = [[UIImageView alloc]initWithFrame:CGRectMake(15, 173, 15, 15)];
        urlimage1.image = [UIImage imageNamed:@"text"];
        [_tongLView addSubview:urlimage1];

        UIImageView *urlimage2 = [[UIImageView alloc]initWithFrame:CGRectMake(15, 203, 15, 15)];
        urlimage2.image = [UIImage imageNamed:@"text"];
        [_tongLView addSubview:urlimage2];

        UIImageView *urlimage3 = [[UIImageView alloc]initWithFrame:CGRectMake(14, 228, 18, 18)];
        urlimage3.image = [UIImage imageNamed:@"字体颜色"];
        [_tongLView addSubview:urlimage3];
        
        UITextField *textview = [[UITextField alloc]initWithFrame:CGRectMake(40, 138, WIDTH-50, 25)];
        textview.tag = 130;
        textview.delegate = self;
        textview.layer.masksToBounds = YES;
        textview.layer.cornerRadius = 6.0;
        textview.layer.borderWidth = 1;
        textview.layer.borderColor = [UIColorFromRGB(0xefeff1) CGColor];
        textview.placeholder = @" 请输入你的微店或移动站点的URL";
        if ([_dataDic objectForKey:@"ad_link"]) {
            textview.text = [_dataDic objectForKey:@"ad_link"];
        }
        textview.font = [UIFont fontWithName:@"Heiti SC" size:12];;
        [_tongLView addSubview:textview];
        
        UITextField *textview1 = [[UITextField alloc]initWithFrame:CGRectMake(40, 168, WIDTH-50, 25)];
        textview1.tag = 131;
        textview1.delegate = self;
        textview1.layer.masksToBounds = YES;
        textview1.layer.cornerRadius = 6.0;
        textview1.layer.borderWidth = 1;
        textview1.layer.borderColor = [UIColorFromRGB(0xefeff1) CGColor];
        textview1.placeholder = @" 请输入广告的标题";
        
        textview1.font = [UIFont fontWithName:@"Heiti SC" size:12];;
        [_tongLView addSubview:textview1];
        UITextField *textview2 = [[UITextField alloc]initWithFrame:CGRectMake(40, 198, WIDTH-50, 25)];
        textview2.tag = 132;
        textview2.delegate = self;
        textview2.layer.masksToBounds = YES;
        textview2.layer.cornerRadius = 6.0;
        textview2.layer.borderWidth = 1;
        textview2.layer.borderColor = [UIColorFromRGB(0xefeff1) CGColor];
        textview2.placeholder = @" 请输入广告的描述语";
    
        textview2.font = [UIFont fontWithName:@"Heiti SC" size:12];;
        [_tongLView addSubview:textview2];
        
        NSArray *color = @[[UIColor redColor],[UIColor yellowColor],[UIColor greenColor],[UIColor cyanColor],[UIColor blueColor],[UIColor purpleColor],[UIColor whiteColor],[UIColor blackColor]];
        for (int i = 0; i < [color count]; i++) {
            UIButton *but = [[UIButton alloc]initWithFrame:CGRectMake(i*(WIDTH/8)- i*10 +(WIDTH - 7*(WIDTH/8)+50)/2, 228, 20, 20)];
            but.backgroundColor = color[i];
            but.layer.masksToBounds = YES;
            but.layer.cornerRadius = 5.0;
            but.layer.borderWidth = 0.5;
            but.layer.borderColor = [UIColorFromRGB(0x333333) CGColor];
            but.tag = i+190;
            [but addTarget:self action:@selector(coloreditBut:) forControlEvents:UIControlEventTouchUpInside];
            [_tongLView addSubview:but];
        }
        
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(10, 248, WIDTH-20, 40)];
        lab.text = @"注:可制作680*120像素图片,链接店铺地址或产品单页等. \n    只有系统广告素材才可添加文字.";
        lab.font = [UIFont fontWithName:@"Heiti SC" size:11];;
        lab.numberOfLines = 0;
        [_tongLView addSubview:lab];
    }
    return _tongLView;
}
- (UIView *)mingPView{
    if (_mingPView == nil) {
        _mingPView = [[UIView alloc]init];
        _mingPView.frame = CGRectMake(0, 52, WIDTH, 300);
        [self.view addSubview:_mingPView];

        _mingPimage = [[UIImageView alloc]initWithFrame:CGRectMake(20, 15, 80, 80)];
        if ([_dataDic objectForKey:@"ad_head"]) {
            [_mingPimage sd_setImageWithURL:[NSURL URLWithString:[_dataDic objectForKey:@"ad_head"]]];
        }else{
            _mingPimage.image = [UIImage imageNamed:@"tuwen"];
        }
        _mingPimage.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonpress:)];
        [_mingPimage addGestureRecognizer:singleTap1];
        [_mingPView addSubview:_mingPimage];

        UITextField *titletextview = [[UITextField alloc]initWithFrame:CGRectMake(110, 20, WIDTH-130, 25)];
        titletextview.tag = 134;
        titletextview.layer.masksToBounds = YES;
        titletextview.layer.cornerRadius = 6.0;
        titletextview.layer.borderWidth = 1;
        titletextview.layer.borderColor = [UIColorFromRGB(0xefeff1) CGColor];
        titletextview.placeholder = @" 请输入标题";
        if ([_dataDic objectForKey:@"ad_card_title"]) {
            titletextview.text = [_dataDic objectForKey:@"ad_card_title"];
        }
        titletextview.font = [UIFont fontWithName:@"Heiti SC" size:12];;
        [_mingPView addSubview:titletextview];
        
        UITextView *describetextview = [[UITextView alloc]initWithFrame:CGRectMake(110, 50, WIDTH-130, 40)];
        describetextview.tag = 135;
        describetextview.layer.masksToBounds = YES;
        describetextview.layer.cornerRadius = 5.0;
        describetextview.layer.borderWidth = 1;
        describetextview.layer.borderColor = [UIColorFromRGB(0xefeff1) CGColor];
        //describetextview.placeholder = @" 请输入描述语";
        if ([_dataDic objectForKey:@"ad_card_description"]) {
            describetextview.text = [_dataDic objectForKey:@"ad_card_description"];
        }
        describetextview.font = [UIFont fontWithName:@"Heiti SC" size:12];;
        [_mingPView addSubview:describetextview];
        
        NSArray *name = @[@"姓名:",@"手机号:",@"地址:",@"QQ号:",@"微信号:"];
        for (int i = 0; i<name.count; i++) {
            UILabel *titlename = [[UILabel alloc]initWithFrame:CGRectMake(10, 100+i*40, 50, 25)];
            titlename.text = [NSString stringWithFormat:@"%@",name[i]];
            titlename.textColor = UIColorFromRGB(0x666666);
            titlename.font = [UIFont systemFontOfSize:13];
            [_mingPView addSubview:titlename];
        }
        
        UITextField *nametextview = [[UITextField alloc]initWithFrame:CGRectMake(60, 100, WIDTH-200, 30)];
        nametextview.tag = 136;
        nametextview.layer.masksToBounds = YES;
        nametextview.layer.cornerRadius = 6.0;
        nametextview.layer.borderWidth = 1;
        nametextview.layer.borderColor = [UIColorFromRGB(0xefeff1) CGColor];
        nametextview.placeholder = @" 请输入姓名";
        if ([_dataDic objectForKey:@"ad_name"]) {
            nametextview.text = [_dataDic objectForKey:@"ad_name"];
        }
        nametextview.font = [UIFont fontWithName:@"Heiti SC" size:12];;
        [_mingPView addSubview:nametextview];

        UITextField *desctextview = [[UITextField alloc]initWithFrame:CGRectMake(60, 140, WIDTH-200, 30)];
        desctextview.tag = 137;
        desctextview.layer.masksToBounds = YES;
        desctextview.layer.cornerRadius = 6.0;
        desctextview.layer.borderWidth = 1;
        desctextview.layer.borderColor = [UIColorFromRGB(0xefeff1) CGColor];
        desctextview.placeholder = @" 请输入手机号";
        if ([_dataDic objectForKey:@"ad_mobile"]) {
            desctextview.text = [_dataDic objectForKey:@"ad_mobile"];
        }
        desctextview.font = [UIFont fontWithName:@"Heiti SC" size:12];;
        [_mingPView addSubview:desctextview];

        UITextField *textview = [[UITextField alloc]initWithFrame:CGRectMake(60, 180, WIDTH-80, 30)];
        textview.tag = 138;
        textview.layer.masksToBounds = YES;
        textview.layer.cornerRadius = 6.0;
        textview.layer.borderWidth = 1;
        textview.layer.borderColor = [UIColorFromRGB(0xefeff1) CGColor];
        textview.placeholder = @" 请输入你的联系地址";
        if ([_dataDic objectForKey:@"ad_address"]) {
            textview.text = [_dataDic objectForKey:@"ad_address"];
        }
        textview.font = [UIFont fontWithName:@"Heiti SC" size:12];;
        [_mingPView addSubview:textview];

        UITextField *QQtextview = [[UITextField alloc]initWithFrame:CGRectMake(60, 220, WIDTH-200, 30)];
        QQtextview.tag = 139;
        QQtextview.layer.masksToBounds = YES;
        QQtextview.layer.cornerRadius = 6.0;
        QQtextview.layer.borderWidth = 1;
        QQtextview.layer.borderColor = [UIColorFromRGB(0xefeff1) CGColor];
        QQtextview.placeholder = @" 请输入QQ号";
        if ([_dataDic objectForKey:@"ad_qq"]) {
            QQtextview.text = [_dataDic objectForKey:@"ad_qq"];
        }
        QQtextview.font = [UIFont fontWithName:@"Heiti SC" size:12];;
        [_mingPView addSubview:QQtextview];
        
        UITextField *WXtextview = [[UITextField alloc]initWithFrame:CGRectMake(60, 260, WIDTH-200, 30)];
        WXtextview.tag = 140;
        WXtextview.layer.masksToBounds = YES;
        WXtextview.layer.cornerRadius = 6.0;
        WXtextview.layer.borderWidth = 1;
        WXtextview.layer.borderColor = [UIColorFromRGB(0xefeff1) CGColor];
        WXtextview.placeholder = @" 请输入微信号";
        if ([_dataDic objectForKey:@"ad_wx"]) {
            WXtextview.text = [_dataDic objectForKey:@"ad_wx"];
        }
        WXtextview.font = [UIFont fontWithName:@"Heiti SC" size:12];;
        [_mingPView addSubview:WXtextview];
    }
    return _mingPView;
}
- (void)coloreditBut:(UIButton*)but{
    for (int i = 190; i < 198; i++) {
        UIButton *button = (id)[self.view viewWithTag:i];
        button.layer.borderWidth = 0.5;
        button.layer.borderColor = [UIColorFromRGB(0x333333) CGColor];
    }
    but.layer.borderWidth = 2.0;
    but.layer.borderColor = [[UIColor orangeColor] CGColor];

    NSArray *color = @[@"#FF0000",@"#FFFF00",@"#00FF00",@"#00FFFF",@"#0000FF",@"#A020F0",@"#FFFFFF",@"#000000"];
    _colorNomer = color[but.tag-190];
}
- (IBAction)cutoutButtonClick:(UIButton *)sender {
    
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"确认删除" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [alert show];
    
    
}
#pragma mark alertview代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        
        NSDictionary *dic = @{@"user_token":[user objectForKey:@"token"],
                              @"ads_id":_ads_id};
        
        AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        [manager POST:DELADS_URL parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
            if ([[responseObject objectForKey:@"status"] intValue] == 1) {
                [self back];
            }
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            if ([MyTools connectedToNetwork] == 0) {
                [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
            }else{
                [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
            }
        }];
    }else if (buttonIndex == 1){
        
    }
    
}
- (void)buttonpress:(UITapGestureRecognizer *)gestureRecognizer{
   UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"手机拍照",@"本地图片", nil];
    [actionSheet showInView:self.view];
}
-(void)singlepress:(UITapGestureRecognizer *)gestureRecognizer{
    
    _action = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"系统素材库",@"手机拍照",@"本地图片", nil];
    [_action showInView:self.view];
}
#pragma mark actionsheet代理，选择相册，选择男女
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    

    if (actionSheet == _action) {
        if (buttonIndex == 0) {
            BannerViewController *banner = [[BannerViewController alloc]init];
            void(^aBlock)(NSString *banner_id,NSString *path_url) = ^(NSString *banner_id,NSString *path_url){
                _banner_id = banner_id;
                [_image sd_setImageWithURL:[NSURL URLWithString:path_url]];
            };
            banner.block = aBlock;
            [self.navigationController pushViewController:banner animated:YES];
        }else if (buttonIndex == 1) {
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                NSLog(@"支持相机");
                _myPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:_myPicker animated:YES completion:nil];
                
            }else{
                NSLog(@"不支持相机");
            }
        }else if (buttonIndex == 2){
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
            {
                NSLog(@"支持图库");
            }
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
            {
                NSLog(@"支持相片库");
            }
            _myPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:_myPicker animated:YES completion:nil];
        }else if (buttonIndex == 3){
            //取消
        }
    }else{
        if (buttonIndex == 0) {
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                NSLog(@"支持相机");
                _myPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:_myPicker animated:YES completion:nil];
                
            }else{
                NSLog(@"不支持相机");
            }
        }else if (buttonIndex == 1){
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
            {
                NSLog(@"支持图库");
            }
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
            {
                NSLog(@"支持相片库");
            }
            _myPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:_myPicker animated:YES completion:nil];
        }else if (buttonIndex == 2){
            //取消
        }
    }
    
}
#pragma mark imagepicker代理
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //取消选取图片
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"取消选取图片");
    }];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //选取图片后回调
    NSLog(@"选取图片");
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    NSData *data;
    
    if ([mediaType isEqualToString:@"public.image"]){
        
        //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出，很原始，哈哈
        UIImage *originImage = [info objectForKey:UIImagePickerControllerEditedImage];
        //图片压缩，因为原图都是很大的，不必要传原图
        UIImage *scaleImage = [self scaleImage:originImage toScale:0.8];
        
        //以下这两步都是比较耗时的操作，最好开一个HUD提示用户，这样体验会好些，不至于阻塞界面
        if (UIImagePNGRepresentation(scaleImage) == nil) {
            //将图片转换为JPG格式的二进制数据
            data = UIImageJPEGRepresentation(scaleImage, 1);
        } else {
            //将图片转换为PNG格式的二进制数据
            data = UIImagePNGRepresentation(scaleImage);
        }
        
        //将二进制数据生成UIImage
        UIImage *image = [UIImage imageWithData:data];
        
        //判断是否剪切
        if ([_ad_cut isEqualToString:@"1"]) {
            
            //将图片传递给截取界面进行截取并设置回调方法（协议）
            CaptureViewController *captureView = [[CaptureViewController alloc] init];
            captureView.delegate = self;
            captureView.image = image;
            //隐藏UIImagePickerController本身的导航栏
            picker.navigationBar.hidden = YES;
            [picker pushViewController:captureView animated:YES];
        }
        else{
            
            
            _image.image = image;
            _mingPimage.image = image;
            [_myPicker dismissViewControllerAnimated:YES completion:nil];
            //////
            
            NSData *imagedata = UIImageJPEGRepresentation(originImage, 0.5);
            
            NSString * urlstr = [NSString stringWithFormat:@"111,%@",[imagedata base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength]];
            NSDictionary *dic = @{@"img":urlstr};
            
            AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
            [manager POST:shangchuan parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                
                if ([[responseObject objectForKey:@"status"] intValue] == 1) {
                    
                    _imageurlstr = [[responseObject objectForKey:@"data"] objectForKey:@"id"];
                }else{
                    [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
                }
            } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                
                if ([MyTools connectedToNetwork] == 0) {
                    [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
                }else{
                    [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
                }
            }];
            
        }
    }
    
}
-(void)passImage:(UIImage *)image
{
    
    _image.image = image;
    
    NSData *imagedata = UIImageJPEGRepresentation(image, 1);
    
    NSString * urlstr = [NSString stringWithFormat:@"111,%@",[imagedata base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength]];
    NSDictionary *dic = @{@"img":urlstr};
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:shangchuan parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([[responseObject objectForKey:@"status"] intValue] == 1) {
            
            _imageurlstr = [[responseObject objectForKey:@"data"] objectForKey:@"id"];
        }else{
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];
}
#pragma mark- 缩放图片
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    for (int i = 130; i<138; i++) {
        UITextField *textview = (id)[self.view viewWithTag:i];
        [textview resignFirstResponder];
    }
}
#pragma mark textfield代理
//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 90 + 50 - (self.view.frame.size.height - 216.0-49-35);//键盘高度216
    NSLog(@"%d",offset);
    [UIView animateWithDuration:0.5 animations:^{
        //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
        if(offset > 0)
            self.view.frame = CGRectMake(0.0f, 64-offset, self.view.frame.size.width, self.view.frame.size.height);
    }];}

//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.5 animations:^{
        self.view.frame =CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
        
    }];
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.translucent = YES;
    self.tabBarController.tabBar.hidden = YES;
    
    }

@end
